package com.example.mybatisdemo.service;

import com.example.mybatisdemo.multi.DbTxConstants;
import com.example.mybatisdemo.multi.MultiTransactional;
import com.example.mybatisdemo.repository.primary.UserPrimaryRepository;
import com.example.mybatisdemo.repository.primary.entity.Account1;
import com.example.mybatisdemo.repository.second.UserSecondRepository;
import com.example.mybatisdemo.repository.second.entity.Account2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    @Autowired
    private UserPrimaryRepository userPrimaryRepository;
    @Autowired
    private UserSecondRepository userSecondRepository;

//    @Transactional(transactionManager = "transactionManagerPrimary")
    @MultiTransactional(value = {DbTxConstants.DB1_TX, DbTxConstants.DB2_TX})
    public void sendMoney(String from, String to, Integer money) {
        Account1 account1 = new Account1();
        account1.setCardNo(from);
        Example<Account1> example = Example.of(account1);
        Account1 fromAccount = userPrimaryRepository.findOne(example).get();
        fromAccount.setMoney(fromAccount.getMoney() - money);
        userPrimaryRepository.save(fromAccount);
        System.out.println(fromAccount);

        int i = 1 / 0;

        Account2 account2 = new Account2();
        account2.setCardNo(to);
        Example<Account2> example2 = Example.of(account2);
        Account2 toAccount = userSecondRepository.findOne(example2).get();
        toAccount.setMoney(toAccount.getMoney() + money);
        userSecondRepository.save(toAccount);
        System.out.println(toAccount);
    }

}
